package de.grosjohann.android.feuerwehr.webservice;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import de.grosjohann.android.feuerwehr.R;
import de.grosjohann.android.feuerwehr.util.PrefsUtil;

public class FMSWsFacade
  extends AbstractWsFacade {

  public static String getFMSStatus(Context ctx) throws ClientProtocolException, IOException, HttpException {
    final String wsUri = "/fms/status";

    FMSWsClient client = createClient(ctx, baseUri + wsUri);
    return client.get();
  }

  public static String setFMSStatusAndLocation(Context ctx, String authorization, String kennung, String status,
      String location) throws ClientProtocolException, IOException, HttpException {
    final String wsUri = "/fms/status";

    FMSWsClient client = createClient(ctx, baseUri + wsUri + "/" + kennung);

    List<BasicNameValuePair> paramList = new ArrayList<BasicNameValuePair>();

    if (status != null) {
      paramList.add(new BasicNameValuePair("status", status));
    }
    if (location != null) {
      paramList.add(new BasicNameValuePair("location", location));
    }

    NameValuePair[] paramArr = new BasicNameValuePair[paramList.size()];
    paramList.toArray(paramArr);

    return client.post(authorization, paramArr);
  }

  public static String getFMSAuthorization(Context ctx, String authorization) throws ClientProtocolException,
    IOException, HttpException {
    final String authUri = "/fms/authorization";

    FMSWsClient client = createClient(ctx, baseUri + authUri + "/" + authorization);
    return client.get();
  }

  private static FMSWsClient createClient(Context ctx, String uri) throws ClientProtocolException, IOException {
    final int connectionTimeout =
        PrefsUtil.getInt(ctx, R.string.prefKeyConnectionTimeout, R.string.prefDefaultConnectionTimeout);
    final int socketTimeout = PrefsUtil.getInt(ctx, R.string.prefKeySocketTimeout, R.string.prefDefaultSocketTimeout);

    return new FMSWsClient(uri, connectionTimeout, socketTimeout);
  }
}
